package cn.ike.web.controller.cargo;

import cn.ike.domain.cargo.Contract;
import cn.ike.domain.cargo.ContractExample;
import cn.ike.domain.system.User;
import cn.ike.service.cargo.ContractService;
import cn.ike.web.controller.BaseController;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.PageInfo;
import lombok.extern.log4j.Log4j;
import org.apache.zookeeper.data.Id;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Log4j
@RequestMapping("/cargo/contract")
public class ContractController extends BaseController {

    @Reference
    private ContractService contractService;

    /**
     * 1.购销合同列表分页
     */
    @RequestMapping("/list")
    public ModelAndView list(
            @RequestParam(defaultValue = "1") Integer pageNum,
            @RequestParam(defaultValue = "5") Integer pageSize) {
        ModelAndView model = new ModelAndView();
        PageInfo<Contract> pageInfo = null;
        try {
            log.info("执行购销合同列表分页查询开始...");
            // 创建查询对象
            ContractExample example = new ContractExample();
            ContractExample.Criteria criteria = example.createCriteria();
            // 根据创建时间倒序排序..
            example.setOrderByClause("create_time desc");
            // 添加查询条件: companyId
            criteria.andCompanyIdEqualTo(getLoginCompanyId());
            /**
             * 细粒度权限控制
             */
            // 获取登陆用户
            User user = getLoginUser();
            // 获取用户等级
            Integer degree = user.getDegree();
            // 判断用户等级
            if (degree == 4){
                //-- 1、普通员工登陆，degree=4,只能查看自己创建的购销合同
                //SELECT * FROM co_contract WHERE create_by='登陆用户的id'
                criteria.andCreateByEqualTo(user.getId());
                // 调用service查询购销合同列表
                pageInfo = contractService.findByPage(example, pageNum, pageSize);
            } else if (degree == 3){
                //-- 2、部门经理登陆，degree=3,可以查看自己部门下所有员工创建的购销合同
                //SELECT * FROM co_contract WHERE create_dept='部门id(登陆用户)'
                criteria.andCreateDeptEqualTo(user.getDeptId());
                // 调用service查询购销合同列表
                pageInfo = contractService.findByPage(example, pageNum, pageSize);
            } else if (degree == 2){
                // 3. 大部门经理登陆，degree=2，可以查看自己部门及其所有子部门创建的购销合同
                //SELECT * FROM co_contract WHERE FIND_IN_SET(create_dept,getDeptChild('登陆用户的部门id'))
                pageInfo = contractService.findContractByDeptId(user.getDeptId(), pageNum, pageSize);
            }
            model.addObject("pageInfo", pageInfo);
            model.setViewName("cargo/contract/contract-list");
            log.info("执行购销合同列表分页查询结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行购销合同列表分页查询出现异常！", e);
        }
        return model;
    }

    /**
     * 2.进入添加购销合同页面
     */
    @RequestMapping("toAdd")
    public ModelAndView toAdd() {
        ModelAndView model = new ModelAndView();
        try {
            log.info("执行添加购销合同页面开始...");
            model.setViewName("cargo/contract/contract-add");
            log.info("执行添加购销合同页面结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行添加购销合同页面出现异常！", e);
        }
        return model;
    }

    /**
     * 3.购销合同的添加或修改
     */
    @RequestMapping("edit")
    public ModelAndView edit(Contract contract) {
        ModelAndView model = new ModelAndView();
        try {
            if (StringUtils.isEmpty(contract.getId())) {
                log.info("执行购销合同的添加开始...");
                // id为空就是添加购销合同
                contract.setCompanyId(getLoginCompanyId());
                contract.setCompanyName(getLoginCompanyName());
                contract.setCreateBy(getLoginUser().getId());
                contract.setCreateDept(getLoginUser().getDeptId());
                contractService.save(contract);
                log.info("执行购销合同的添加结束...");
            } else {
                log.info("执行购销合同的修改开始...");
                // 否则就是更新购销合同
                contractService.update(contract);
                log.info("执行购销合同的修改结束...");
            }
            model.setViewName("redirect:/cargo/contract/list");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行购销合同的添加或修改出现异常！", e);
        }
        return model;
    }

    /**
     * 4.修改购销合同信息数据回显
     */
    @RequestMapping("toUpdate")
    public ModelAndView toUpdate(String contractId) {
        ModelAndView model = new ModelAndView();
        try {
            log.info("执行修改购销合同信息开始...");
            Contract contract = contractService.findById(contractId);
            model.addObject("contract",contract);
            model.setViewName("/cargo/contract/contract-update");
            log.info("执行修改购销合同信息结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行修改购销合同信息出现异常！", e);
        }
        return model;
    }

    /**
     * 5.删除购销合同
     */
    @RequestMapping("delete")
    @ResponseBody
    public Map<String, String> delete(String contractId) {
        Map<String, String> map = new HashMap<>();
        try {
            log.info("执行删除购销合同的开始...");
            boolean flag = contractService.delete(contractId);
            if (flag){
                map.put("msg", "删除成功！");
            } else {
                map.put("msg", "删除失败：当前删除的购销合同被外键引用！");
            }
            log.info("执行删除购销合同的结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行删除购销合同的出现异常！", e);
        }
        return map;
    }

    /**
     * 查看购销合同信息
     */
    @RequestMapping("toView")
    public ModelAndView toView(String contractId) {
        ModelAndView model = new ModelAndView();
        try {
            log.info("执行查看购销合同开始...");
            Contract contract = contractService.findById(contractId);
            model.addObject("contract", contract);
            model.setViewName("/cargo/contract/contract-view");
            log.info("执行查看购销合同结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行查看购销合同出现异常！", e);
        }
        return model;
    }

    /**
     * 修改购销合同的状态
     */
    @RequestMapping("submit")
    public String submit(String contractId) {
        try {
            log.info("执行修改购销合同状态开始...");
            Contract contract = contractService.findById(contractId);
            if (contract != null){
                contract.setState(1);
            }
            contractService.update(contract);
            log.info("执行修改购销合同状态结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行修改购销合同状态出现异常！", e);
        }
        return "redirect:/cargo/contract/list";
    }

    /**
     * 修改购销合同的状态
     */
    @RequestMapping("cancel")
    public String cancel(String contractId) {
        try {
            log.info("执行修改购销合同状态开始...");
            Contract contract = contractService.findById(contractId);
            if (contract != null){
                contract.setState(0);
            }
            contractService.update(contract);
            log.info("执行修改购销合同状态结束...");
        } catch (Exception e) {
            e.printStackTrace();
            log.error("执行修改购销合同状态出现异常！", e);
        }
        return "redirect:/cargo/contract/list";
    }

}
